package com.jiantong.web.open.app.work;

import com.jiantong.common.util.UserUtil;
import com.jiantong.user.ext.LoginUser;
import com.jiantong.user.model.BreedFactory;
import com.jiantong.user.service.BreedFactoryReadService;
import com.jiantong.web.core.enums.ExceptionCode;
import com.jiantong.work.model.SeedPurchaseRecord;
import com.jiantong.work.service.SeedPurchaseRecordReadService;
import com.jiantong.work.service.SeedPurchaseRecordWriteService;
import io.terminus.boot.rpc.common.annotation.RpcConsumer;
import io.terminus.common.model.Paging;
import io.terminus.common.model.Response;
import io.terminus.pampas.openplatform.annotations.OpenBean;
import io.terminus.pampas.openplatform.annotations.OpenMethod;
import io.terminus.pampas.openplatform.exceptions.OPClientException;
import io.terminus.pampas.openplatform.exceptions.OPServerException;
import lombok.extern.slf4j.Slf4j;
import org.assertj.core.util.Strings;
import org.joda.time.DateTime;
import org.springframework.web.bind.annotation.RequestMethod;

import java.util.ArrayList;
import java.util.Date;
import java.util.Map;

/**
 * 引种记录
 * Created by maowenjie on 2017/4/18.
 */
@Slf4j
@OpenBean
public class SeedPurchaseRecordApis {
    @RpcConsumer
    private SeedPurchaseRecordReadService seedPurchaseRecordReadService;

    @RpcConsumer
    private SeedPurchaseRecordWriteService seedPurchaseRecordWriteService;

    @RpcConsumer
    private BreedFactoryReadService breedFactoryReadService;

    /**
     * find By id
     * @param id
     * @return
     */
    @OpenMethod(
            key = "find.introduction.record.by.id",
            paramNames = {"id"},
            httpMethods = RequestMethod.GET
    )
    public SeedPurchaseRecord findById(Long id){
        if (id == null){
            log.error("is should be not null");
            throw new OPClientException(ExceptionCode.ID_NOT_EXIST.value(),"is should be not null");
        }
        Response<SeedPurchaseRecord> response = seedPurchaseRecordReadService.findById(id);
        if(!response.isSuccess()){
            log.error("failed to find SeedPurchaseRecord , cause : {}", response.getError());
            throw new OPServerException(ExceptionCode.DATA_NOT_FOUND.value(),response.getError());
        }
        return response.getResult();
    }

    /**
     * 根据状态分页查询引种记录
     * @param pageNo
     * @param pageSize
     * @param status
     * @return
     */
    @OpenMethod(
            key = "paging.introduction.record",
            paramNames = {"pageNo","pageSize","breedFactoryId","status"},
            httpMethods = RequestMethod.GET
    )
    public Paging<SeedPurchaseRecord> pagingSeedPurchaseRecord(Integer pageNo, Integer pageSize,Long breedFactoryId, Integer status){
        if (breedFactoryId == null){
            log.error("breedFactoryId is should be not null");
            throw new OPClientException(ExceptionCode.PARAMETER_NOT_EXIST.value(),"breedFactoryId is should be not null");
        }
        Response<Paging<SeedPurchaseRecord>> response = seedPurchaseRecordReadService.pagingSeedPurchaseRecord(pageNo,pageSize,breedFactoryId,status);
        if(!response.isSuccess()){
            log.error("failed to paging seedPurchaseRecord farm , cause : {}", response.getError());
            throw new OPServerException(ExceptionCode.DATA_NOT_FOUND.value(),response.getError());
        }
        return response.getResult();
    }

    /**
     *  创建引种记录
     * @param seedPurchaseRecord
     * @param toStatus
     * @return
     */
    @OpenMethod(
            key = "create.introduction.record",
            paramNames = {"introductionRecord","toStatus"},
            httpMethods = RequestMethod.POST
    )
    public Map<String , Object> createSeedPurchaseRecord(SeedPurchaseRecord seedPurchaseRecord , Integer toStatus){
        LoginUser loginUser = UserUtil.getCurrentUser();
        BreedFactory breedFactory = breedFactoryReadService.findById(loginUser.getOrganizationId()).getResult();
        if(breedFactory.getIsScale() != 1){
            log.error("this is san hu");
            throw new OPClientException("this is san hu");
        }
        Response<Map<String , Object>> response = seedPurchaseRecordWriteService.createSeedPurchaseRecord(seedPurchaseRecord,toStatus);
        if(!response.isSuccess()){
            log.error("failed to create seedPurchaseRecord, cause : {}",seedPurchaseRecord,toStatus,response.getError());
            throw new OPServerException(ExceptionCode.DATA_NOT_FOUND.value(),response.getError());
        }
        return response.getResult();
    }

    /**
     * 根据toStatus 更新记录状态
     * @param seedPurchaseRecord
     * @param toStatus
     * @return
     */
    @OpenMethod(
            key = "update.introduction.record",
            paramNames = {"introductionRecord","toStatus"},
            httpMethods = RequestMethod.PUT
    )
    public  Map<String , Object> updateSeedPurchaseRecord(SeedPurchaseRecord seedPurchaseRecord , Integer toStatus){
        if(seedPurchaseRecord.getId() == null){
            log.error("failed to update seedPurchaseRecord error = {}, cause : {}", seedPurchaseRecord,seedPurchaseRecord.getId());
            throw new OPClientException(ExceptionCode.ID_NOT_EXIST.value(),"seedPurchaseRecord.id.is.null");
        }

        Response<Map<String , Object>> statusResponse = seedPurchaseRecordReadService.findStatusById(seedPurchaseRecord.getId());
        if(statusResponse.isSuccess() && !statusResponse.getResult().get("status").equals(seedPurchaseRecord.getStatus())){
            log.error("seedPurchaseRecord is already submitted error = {}, cause : {}", seedPurchaseRecord.getStatus(),statusResponse.getResult().get("status"));
            throw new OPClientException("this.report.is.already.submitted");
        }

        Response<Map<String , Object>> response = seedPurchaseRecordWriteService.updateSeedPurchaseRecord(seedPurchaseRecord,toStatus);
        if(!response.isSuccess()){
            log.error("failed to update seedPurchaseRecord error = {}, cause : {}", seedPurchaseRecord, response.getError());
            throw new OPServerException(ExceptionCode.DATA_UPDATE_FAIL.value(),response.getError());
        }
        return response.getResult();
    }

    @OpenMethod(
            key = "paging.status.introduction.record",
            paramNames = {"pageNo", "pageSize", "breedFactoryId","breedType", "fromDate", "toDate"},
            httpMethods = RequestMethod.GET)
    public Paging<SeedPurchaseRecord> pagingSeedPurchaseRecord(Integer pageNo,
                                                                     Integer pageSize,
                                                                     Long breedFactoryId,
                                                               Integer breedType,
                                                                     String fromDate,
                                                                     String toDate) {
        Date start = null;
        if (!Strings.isNullOrEmpty(fromDate)) {
            start = DateTime.parse(fromDate).toDate();
        }

        Date end = null;
        if (!Strings.isNullOrEmpty(toDate)) {
            end = DateTime.parse(toDate).toDate();
        }
        Response<Paging<SeedPurchaseRecord>> resp = seedPurchaseRecordReadService
                .pagingSeedPurchaseRecordGqv(pageNo, pageSize, breedFactoryId,breedType, start, end);
        if (!resp.isSuccess()) {
            log.error("failed to paging seed purchase record{}, cause : {}", resp.getError());
            throw new OPServerException(ExceptionCode.DATA_NOT_FOUND.value(),resp.getError());
        }
        return resp.getResult();
    }
}
